package com.system.service.monitor.task.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.constant.ScheduleConstants;
import com.system.entity.monitor.task.Taskinfo;
import com.system.entity.monitor.task.TaskinfoLogs;
import com.system.mapper.monitor.task.TaskinfoLogsMapper;
import com.system.mapper.monitor.task.TaskinfoMapper;
import com.system.response.monitor.task.TaskDtoResponse;
import com.system.service.monitor.task.TaskService;
import com.system.util.RedisUtils;
import com.system.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * @Classname TaskServiceImpl
 * @Date 2023/8/4 13:49
 * @Created ZFC
 */
@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskinfoMapper, Taskinfo> implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 添加任务
     * @param task
     * @return
     */
    @Override
    public long addTask(TaskDtoResponse task) {
        //1、添加日志到数据库
        boolean success = this.insertTaskInfo(task);
        if (success) {
            //2、添加日志到redis
            addTaskToCache(task);
        }
        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flg = false;
        //1、删除数据库中的数据
        TaskDtoResponse success = updateDb(taskId, ScheduleConstants.CANCELLED);

        //2、删除缓存中的数据
        if (success != null) {
            removeTaskFromCache(success);
            flg = true;
        }
        return flg;
    }

    /**
     * 消费任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public TaskDtoResponse poll(int type, int priority) {
        //1、获取缓存数据
        TaskDtoResponse task = null;
        try {
            String k = type + "_" + priority;

            String task_json = redisUtils.lPop(ScheduleConstants.TOPIC + k);
            if (StringUtils.isNotEmpty(task_json)) {

                task = JSON.parseObject(task_json, TaskDtoResponse.class);
                //更新数据库信息
                this.updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("poll task exception");
        }

        return task;
    }

    /**
     * 未来数据刷新
     */
//    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        // 获取所有未来数据集合的key值
        Set<String> futureKeys = redisUtils.scan(ScheduleConstants.FUTURE + "*");

        for (String futureKey : futureKeys) {
            //key
            String k = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
            //获取该组key下当前需要消费的任务数据
            Set<Object> tasks = redisUtils.zRangeByScore(futureKey, 0, System.currentTimeMillis());

            if (!tasks.isEmpty()){
                //将这些任务数据添加到消费者队列中
                redisUtils.refreshWithPipeline(futureKey, k, tasks);
            }
        }
    }

//    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct
    public void reloadData(){
        //1、删除缓存中未来数据集合和当前消费者队列的所有key
        clearCache();
        log.info("数据库同步数据到缓存");

        //获取5分钟之后的时间  毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(calendar.MINUTE, 5);

        //查看小于未来5分钟的所有任务
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(
                new LambdaQueryWrapper<Taskinfo>()
                        .le(Taskinfo::getExecuteTime, calendar.getTime())
        );
        taskinfos.stream().forEach(val->{
            TaskDtoResponse taskDto = new TaskDtoResponse();
            BeanUtils.copyProperties(val,taskDto);
            taskDto.setExecuteTime(val.getExecuteTime().getTime());
            addTaskToCache(taskDto);

        });
    }

    /**
     * 删除缓存中未来数据集合和当前消费者队列的所有key
     */
    private void clearCache() {
        // 获取所有未来数据集合的key值
        Set<String> futureKeys = redisUtils.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = redisUtils.scan(ScheduleConstants.TOPIC + "*");
        //删除缓存中未来数据集合和当前消费者队列的所有key
        redisUtils.delete(futureKeys);
        redisUtils.delete(topicKeys);
    }

    /**
     * 删除redis中的任务数据
     *
     * @param task
     */
    private void removeTaskFromCache(TaskDtoResponse task) {

        String k = task.getExecuteTime() + "_" + task.getPriority();
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //先删除list中的数据
            redisUtils.lRemove(ScheduleConstants.TOPIC + k, 0, JSON.toJSONString(task));
        } else {
            //在删除set中的数据
            redisUtils.zRemove(ScheduleConstants.FUTURE + k, JSON.toJSONString(task));
        }
    }

    /**
     * 更新数据库信息
     * @param taskId
     * @param status
     * @return
     */
    private TaskDtoResponse updateDb(long taskId, int status) {
        TaskDtoResponse task = null;

        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);

            //更新任务日志的状态
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            log.info("数据：{}", taskinfoLogs);

            //然后taskdto
            task = new TaskDtoResponse();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("task cancel exception taskid={}", taskId);
        }
        return task;
    }

    /**
     * 添加任务到redis中
     *
     * @param task
     */
    private void addTaskToCache(TaskDtoResponse task) {
        //1.1 判断当前任务的时间是否是当前时间

        String k = task.getTaskType() + "_" + task.getPriority();

        //获取5分钟之后的时间  毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(calendar.MINUTE, 5);
        long nextScheduleTime = calendar.getTimeInMillis();

        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //2.1 如果任务的执行时间小于等于当前时间，存入list
            redisUtils.lPush(ScheduleConstants.TOPIC + k, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= nextScheduleTime) {
            //2.2 如果任务的执行时间大于当前时间 && 小于等于预设时间（未来5分钟） 存入zset中
            redisUtils.zAdd(ScheduleConstants.FUTURE + k, JSON.toJSONString(task), task.getExecuteTime());
        }

    }

    /**
     * 将数据存入数据库
     *
     * @param task
     */
    private boolean insertTaskInfo(TaskDtoResponse task) {
        try {
            log.info("将数据存入数据库中 :{}", task);
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskID
            task.setTaskId(taskinfo.getTaskId());
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
